#!/bin/bash
###############################################配置###################################################
#配置工作空间，systemctl执行$pwd拿不到脚本目录
APP_HOME="/opt/project/app"
#APP_HOME=$(pwd) 
# 应用jar包的名字
APP_NAME="app_name"
# 环境配置文件，如application-dev.yml,pro,test
PROFILE="env"
# logs为日志存储路径
LOG_PATH=$APP_HOME/logs
# GC日志参数
GC_LOG_OPTS=" -XX:+PrintGC -XX:+PrintGCDetails -Xloggc:$LOG_PATH/gc-%t.log"
# GC收集器参数
GC_OPTS=""
#GC_OPTS="-XX:+UseConcMarkSweepGC"
DEBUG_OPTS=""
#DEBUG_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y"
# 其他参数
OTHER_OPTS="-Dspring.profiles.active=$PROFILE"
# JVM 启动参数
JVM_OPTIONS="-server -Xms4096M -Xmx4096M -XX:MaxMetaspaceSize=1024M $DEBUG_OPTS $GC_OPTS $GC_LOG_OPTS $OTHER_OPTS"
################################################配置###################################################
JAR_NAME="$APP_NAME.jar"
JAR_PATH=$APP_HOME/$JAR_NAME
PID="$APP_NAME.pid"
PID_PATH=$APP_HOME/$PID

# 配置JAVA_HOME
#export JAVA_HOME=/usr/java/latest/
#export PATH=$JAVA_HOME/bin:$PATH
# 创建日志目录
function mkdir_logs()
{
    # 创建log路径
    if [ ! -d $LOG_PATH ]; then
    mkdir $LOG_PATH
    fi
}
# 使用说明，用来提示输入参数
function usage()
{
  echo "Usage: app.sh [start|stop|restart|status]"
  exit 1
}
# 检查程序是否在运行
function is_exist()
{
  pid=$(ps -ef | grep $JAR_PATH | grep -v grep | awk '{print $2}')
  #如果不存在返回1，存在返回0
  if [ -z "${pid}" ]; then
    return 1
  else
    return 0
  fi
}
# 启动方法
function start()
{
  is_exist
  if [ $? -eq "0" ]; then
    echo "WARN: $JAR_NAME is already running PID=${pid}"
  else
    mkdir_logs
    rm -f $APP_HOME/nohup.log
    echo "JVM_OPTIONS : "
    echo $JVM_OPTIONS | sed 's/ /\n/g '
    #nohup java -jar $JVM_OPTIONS $JAR_PATH >> $APP_HOME/nohup.log 2>&1 &
    nohup java -jar $JVM_OPTIONS $JAR_PATH >> /dev/null 2>&1 &
    echo $! > $PID_PATH
    echo "INFO: start $JAR_NAME successed PID=$!"
  fi
}
# 停止方法
function stop()
{  
  pid=$(ps -ef | grep $JAR_PATH | grep -v grep | awk '{print $2}')
  echo "INFO: JAR_PATH=$JAR_PATH, PID = ${pid}"
  if [ ! -z "${pid}" ]; then
    echo "INFO: app PID = ${pid} begin kill -9 ${pid}"
    kill -9 ${pid}
    sleep 2
    echo "INFO: $JAR_NAME process stopped ---"
  else
    echo "INFO: $JAR_NAME is not running ---"
  fi
}
# 输出运行状态
function status()
{
  is_exist
  if [ $? -eq "0" ]; then
    echo "INFO: $JAR_NAME is running PID is $pid"
  else
    echo "WARN: $JAR_NAME is not running"
  fi
}
# 重启
function restart() {
  stop
  start
}
 
case "$1" in
"start")
  start
  ;;
"stop")
  stop
  ;;
"status")
  status
  ;;
"restart")
  restart
  ;;
*)
  usage
  ;;
esac
exit 0